using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;

namespace Scurvy.Media.Audio
{
    public class TimedAudio : IDisposable
    {
        #region fields
        private AudioEngine _audioEngine;
        private WaveBank _waveBank;
        private SoundBank _soundBank;

        private bool _playing;
        private double _timeStarted;
        private int _currentBeat;
        #endregion

        #region Constructors
        public TimedAudio(string enginePath, string wavePath, string soundPath)
            :
            this(new AudioEngine(enginePath), wavePath, soundPath)
        { }

        public TimedAudio(AudioEngine engine, string wavePath, string soundPath)
        {
            _audioEngine = engine;
            _waveBank = new WaveBank(engine, wavePath);
            _soundBank = new SoundBank(_audioEngine, soundPath);
        }
        #endregion

        public void Update(GameTime gameTime)
        {
            _audioEngine.Update();

            float bpm = 120 / 8;
            float msBetweenBeats = (60 / bpm) * 1000;
            double currentTime = gameTime.TotalGameTime.TotalSeconds;

            if (!_playing && _waveBank.IsPrepared)
            {
                _playing = true;
                _timeStarted = currentTime;
                _soundBank.PlayCue("clicktrack");
            }

            if (_playing)
            {
                double timePassed = currentTime - _timeStarted;
                int beats = (int)(timePassed / (bpm / 60));
                if (beats != _currentBeat)
                {
                    _currentBeat = beats;
                    //_soundBank.PlayCue("click");
                    //raise event
                }
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            _soundBank.Dispose();
            _waveBank.Dispose();
            _audioEngine.Dispose();
        }

        #endregion
    }
}